import { useState, useEffect } from 'react';
import { useRequest } from 'ahooks';
import { Badge, Button, Table } from 'antd';
import { useHistory } from 'react-router-dom';

import * as APIS from '../../../../constants/api-constants';

interface Props {
  uuid: string;
}

/**
 * 问卷table
 * @param record 当前问卷模板
 * @returns Qurstionnaire table
 */
const ExpandedRowRender = (recordTemplate: Props) => {
  const [questionnaireDataSource, setQuestionnaireDataSource] = useState([]);
  const history = useHistory();
  const { uuid } = recordTemplate;

  /**
   * 获取当前模板对应的问卷列表
   */
  const handleQuestionnaire = useRequest((data) => {
    const questionUuid = data;
    return {
      url: APIS.QUESTIONNAIRE_LIST,
      method: 'GET',
      params: {
        uuid: questionUuid
      }
    };
  }, {
    manual: true,
    onSuccess: (result) => {
      const { questionnaires: currentQuestionnaires } = result.data;

      return currentQuestionnaires;
    },
  });

  useEffect(() => {
    if (uuid) {
      (async () => {
        const curQuestionnaireDataSource = await handleQuestionnaire
          .run(
            uuid
          );
        setQuestionnaireDataSource(
          curQuestionnaireDataSource?.data?.questionnaires ?? []
        );
      })();
    }
  }, [uuid]);

  const columns = [
    { title: '问卷标题', dataIndex: 'name', key: 'name' },
    {
      title: '问卷开启状态',
      key: 'open',
      dataIndex: 'open',
      width: 150,
      render: (record: number) => (
        record ? (
          <span>
            <Badge status="success" />
            开启
          </span>
        ) : (
          <span>
            <Badge status="error" />
            关闭
          </span>
        )
      )
    },
    {
      title: '操作',
      width: 150,
      dataIndex: 'operation',
      key: 'operation',
      render: (text: any,
        record: Questionnaire.QuestionnaireItem,) => (
          <Button
            type="link"
            onClick={() => {
              history.push(`/home/questionnaireDetail/${uuid}/${record.uuid}`);
            }}
          >
            详情
          </Button>
      )

      ,
    },
  ];

  return (
    <Table
      columns={columns}
      loading={handleQuestionnaire.loading}
      rowKey={(questionnaire) => questionnaire.uuid}
      dataSource={questionnaireDataSource}
      pagination={false}
    />
  );
};

export default ExpandedRowRender;
